<template>
  <a-modal
    title='人员列表'
    :width='width'
    :visible='visible'
    :maskClosable='false'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
    @cancel='handleCancel'>

    <a-row :gutter='10' style='background-color: #ececec; padding: 10px; margin: -10px'>
      <a-col :md='24' :sm='24' id='selectArea'>
        <a-card :bordered='false'>
          用户名：
          <a-input
            :style="{width:'200px',marginBottom:'15px'}"
            placeholder='请输入用户名' @pressEnter='onSearch'
            v-model='queryParam.realname'></a-input>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;部门名：
          <a-input
            :style="{width:'200px',marginBottom:'15px'}"
            placeholder='请输入部门名' @pressEnter='onSearch'
            v-model='queryParam.departName'></a-input>
          <a-button @click='onSearch' style='margin-left: 40px' icon='search' size='small'>查询</a-button>
          <a-button @click='searchReset(1)' style='margin:0 20px' icon='redo' size='small'>重置</a-button>
          <!--用户列表-->
          <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
            <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
            style='font-weight: 600;color:rgba(0, 0, 0, 0.65)'>{{ selectionRowsName }}</a>
            <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
          </div>
          <a-table
            ref='table'
            bordered
            size='middle'
            rowKey='id'
            :columns='columns'
            :dataSource='dataSource'
            :pagination='ipagination'
            :loading='loading'
            :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,onSelect:onSelectSingle,onSelectAll:onSelectAll}'
            @change='handleTableChange'>

            <template slot='roleName' slot-scope='text'>
              <j-ellipsis :value='text' :length='10'></j-ellipsis>
            </template>

          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </a-modal>
</template>
<script>
import { getUserList } from '@/api/api'
import { filterObj } from '@/utils/util'
import { deleteAction, getAction, downFile, postAction } from '@/api/manage'
import JEllipsis from '@comp/jeecg/JEllipsis'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'

export default {
  name: 'ActSelectUserModal',
  components: { JEllipsis },
  data() {
    return {
      visible: false,
      model: {},
      width: `${window.innerWidth * 0.8}px`,
      confirmLoading: false,
      title: '选择人员',
      queryParam: {
        realname: '',
        departName: ''
      },
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'username'
        },
        {
          title: '用户名',
          align: 'center',
          dataIndex: 'realname'
        },
        {
          title: '性别',
          align: 'center',
          dataIndex: 'sex_dictText'
        },
        {
          title: '手机号码',
          align: 'center',
          dataIndex: 'phone'
        },
        {
          title: '所属部门',
          align: 'center',
          dataIndex: 'departName'
        },
        {
          title: '角色',
          align: 'center',
          dataIndex: 'roleName',
          scopedSlots: { customRender: 'roleName' }
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status_dictText'
        }
      ],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      url: {
        list: '/sys/user/list',
        imgerver: window._CONFIG['domianURL'] + '/sys/common/view'
      },
      tokenHeader: {
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)
      },
      /* 数据源 */
      dataSource: [],
      /* 排序参数 */
      isorter: {
        column: '',//不传column 默认sys/user/list接口按realname排序
        order: ''
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectionRowsName: '',            //用来显示选择的所有人员
      productListSelectedRowsPlus: []   //这里是解决Table组件selectedRows翻页后不保留上一页已选中items的解决方案
    }
  },
  methods: {
    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams()//查询条件
      getAction(this.url.list, params).then(res => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
      }).finally(() => {
        this.loading = false
      })
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    open(record) {
      this.model = record
      //回显已选的用户
      this.handleKeys(record)
      this.visible = true
      this.loadData(1)
    },
    //回显已选的用户
    handleKeys(record) {
      if (JSON.stringify(record) !== '{}') {
        var splitIds = record.userIds ? record.userIds.split(',') : []
        var splitNames = record.userNames ? record.userNames.split(',') : []
        var selectArrayList = []
        splitIds.forEach((item, index) => {
          var obj = {
            id: item,
            realname: splitNames[index]
          }
          selectArrayList.push(obj)
        })
        this.selectedRowKeys = splitIds
        this.productListSelectedRowsPlus = selectArrayList
        this.handlePageSize()
      } else {
        this.selectedRowKeys = []
        this.productListSelectedRowsPlus = []
      }
    },
    handleCancel() {
      this.close()
    },
    handleSubmit() {
      const that = this
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning('请至少选择一条数据!')
        return
      } else {
        this.$emit('ok', this.productListSelectedRowsPlus)
        this.close()
      }
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam, this.isorter)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      let str = 'id,'
      for (let a = 0; a < this.columns.length; a++) {
        str += ',' + this.columns[a].dataIndex
      }
      return str
    },
    onSearch() {
      this.loadData(1)
    },
    searchReset(num) {
      let that = this
      if (num !== 0) {
        that.queryParam = {}
        that.loadData(1)
      }
    },
    close() {
      this.searchReset(0)
      this.visible = false
      this.queryParam = {}
      this.ipagination.current = 1
      this.ipagination.pageSize = 10
      this.dataSource = []
      this.selectedRowKeys = []
      this.selectedRows = []
      this.selectionRowsName = ''
      this.productListSelectedRowsPlus = []
      this.model = {}
    },
    getAvatarView: function(avatar) {
      return this.url.imgerver + '/' + avatar
    },
    /*Table组件selectedRows翻页后不保留上一页已选中items的解决方案  用户手动选择/取消选择某列的回调*/
    onSelectSingle(record, selected, selectedRows, nativeEvent) {
      //选中之后
      if (selected) {
        let selectedRowsPlus = this.productListSelectedRowsPlus
        selectedRowsPlus.push(record)
      }
      //去掉选中
      if (!selected) {
        let delIndex = null
        for (let i = 0; i < this.productListSelectedRowsPlus.length; i++) {
          if (this.productListSelectedRowsPlus[i].id == record.id) {
            delIndex = i
            break
          }
        }
        this.productListSelectedRowsPlus.splice(delIndex, 1)
      }
      this.handlePageSize()
    },
    /*Table组件selectedRows翻页后不保留上一页已选中items的解决方案  用户手动选择/取消选择所有列的回调*/
    onSelectAll(selected, selectedRows, changeRows) {
      if (selected) {
        this.productListSelectedRowsPlus = this.productListSelectedRowsPlus.concat(changeRows)
      }
      if (!selected) {
        /*深拷贝*/
        let productListSelectedRowsPlus = JSON.parse(JSON.stringify(this.productListSelectedRowsPlus))
        let delIndex = []
        for (let i = 0; i < productListSelectedRowsPlus.length; i++) {
          for (let j = 0; j < changeRows.length; j++) {
            if (changeRows[j].id == productListSelectedRowsPlus[i].id) {
              delIndex.push(i)
              break
            }
          }
        }
        for (let k = 0; k < delIndex.length; k++) {
          delete productListSelectedRowsPlus[delIndex[k]]
        }
        let pureProductListSelected = productListSelectedRowsPlus.filter((item => {
          return item != undefined
        }))
        this.productListSelectedRowsPlus = pureProductListSelected
      }
      this.handlePageSize()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectedRows
    },
    onClearSelected() {
      this.searchReset(1)
      this.selectedRowKeys = []
      this.selectedKeys = []
      this.selectionRowsName = ''
      this.productListSelectedRowsPlus = []
    },
    /*处理Table组件selectedRows翻页后不保留上一页已选中items的解决方案*/
    handlePageSize() {
      var rowsName = []
      if (this.selectedRowKeys.length !== 0) {
        if (this.productListSelectedRowsPlus.length !== 0) {
          for (var h = 0; h < this.selectedRowKeys.length; h++) {
            for (var a = 0; a < this.productListSelectedRowsPlus.length; a++) {
              if (this.selectedRowKeys[h] === this.productListSelectedRowsPlus[a].id) {
                rowsName.push(this.productListSelectedRowsPlus[a].realname)
              }
            }
          }
          this.selectionRowsName = rowsName + ''
        } else {
          this.selectionRowsName = ''
        }
      } else {
        this.selectionRowsName = ''
      }
      // console.log(this.selectionRowsName)
    }
  }
}
</script>